/**
 * 将带有父节点的集合转为树结构
 * @param items
 * @param rootId 构建树的根节点，默认为 0
 * @param config 树节点配置，默认配置为 { id: 'id', parentId: 'parentId', children: 'children' }
 * @returns 树结构
 */
export function toTree(
  items: any[],
  rootId: number | string = 0,
  config: { children?: string; id?: string; parentId?: string } = {},
) {
  if (!Array.isArray(items)) {
    return [];
  }

  const prop = Object.assign(
    {
      id: 'id',
      parentId: 'parentId',
      children: 'children',
    },
    config,
  );
  const children = items.filter((item) => item[prop.parentId] === rootId);
  for (const item of children) {
    item[prop.children] = toTree(items, item[prop.id]);
  }
  return children;
}
